<?php
namespace app\admin\controller;

use app\admin\model\AuthGroup;
use app\admin\validate\GroupValidate as gv;
use think\Request;
use app\admin\model\Admin as Am;

class Admin extends Auth
{

    //不需要验证的权限
    protected $public_action=['edit','info'];


    //修改账号信息
    //*+------------------------------------------------------------------------+*/

    //修改账号信息
    public function info(){
        $obj = model('admin');
        $info=$obj->where('id','=',UID)->find();

        if(request()->isAjax() || request()->isPost()){
            $realname = input('realname','','trim');
            $password = input('pwd','','trim');
            if($info['realname']==$realname && empty($password))return $this->success('修改成功');

            //只修改姓名时
            if(!$password){
                $data['realname']=$realname;
                $obj->save($data,['id'=>UID]);
                return $this->success('修改成功');
            }

            //原密码
            if($info['password']!=md5($password))$this->error('原密码不正确');

            //新密码
            $newpwd=input('newpwd','','trim');
            if(!$newpwd)$this->error('请输入新密码');
            if(!checkPwd($newpwd))$this->error('新密码格式不正确');

            //确认密码
            $repwd = input('repwd');
            if(!$repwd)$this->error('请输入确认密码');
            if($repwd!=$newpwd)$this->error('确认密码不正确');

            $data['realname'] = $realname ;
            $data['password'] = md5($newpwd);
            $obj->save($data,['id'=>UID]);
            return $this->success('修改成功');
        }


        $this->assign('info',$info);
        $this->lastlogin($info);

        return $this->fetch();
    }


    //最后登录数据
    public function lastlogin($info){
        if(!empty($info['lastloginlog'])){
            $log = string2array($info['lastloginlog']);
            if($log[1]){
                $logary = explode('|', $log[1]);
                $lastlogin = date('Y-m-d H:i:s',$logary[0]).' | '.$logary[1];
            }else{
                $lastlogin = false ;
            }
        }

        $this->assign('lastlogin',$lastlogin);
    }


    //账号管理
    //*+------------------------------------------------------------------------+*/


    //账号列表 首页
    public function index(){
        $cols = "id,account,lastlogintime,lastloginip,realname,state,logincount";
        $map = [ ['hide_flag',"eq",0], ['id','neq',1] ];
        $pagesize=20;
        $res = AM::where($map)->field($cols)->paginate($pagesize);  //  数据分页 查询
        $admin = config('admin.USER_ADMINISTRATOR');
        $list = $res->toArray()['data'];
        return view('',compact("list","admin","res","uid"));
    }


    //添加修改 账号
    public function edit(){
        $id = input('id',0);
    	if(request()->isPost()){
            $data = request()->post();

            //数据验证
            $validate = 'app\admin\validate\AdminValidate';
            if($id)$validate .='.update';
            $result = $this->validate($data,$validate);
            if(true !== $result)return $this->error($result);

            //密码处理
    		if($data['password']){
                $data['password'] = md5($data['password']);
             }else{
                unset($data['password']);
            }

    		//权限数组
            $data['groups'] = $data['group']?implode(',', $data['group']):'';

    		//新增数据时需要添加注册时间
    		if(!$id)$data['time']=time();

            //添加修改数据
    		$this->editDataMethod($data,'admin');
    	}

    	//修改操作
    	if($id){
    		$map['id']=$id;
            $user = model('admin')->where($map)->find();
    		$this->assign('roles',explode(',', $user['groups']));
    		$this->assign('info',$user);
    	}

        $group = db('auth_group')->field('id,title')->where('state',1)->where('hide_flag',0)->order('sort desc,id asc')->select();
        return  view('',compact(['group']));
    }


    //删除（隐藏）账号
    public function remove(){
		$id = input('id');
		$map['id']=$id;
		$object=model('admin');
		$info=$object->where($map)->find();
		if(!$info)$this->error('账号不存在');
		$data['account']='#delete_'.$info['account'];
		$data['hide_flag']=1;
		if(false===model('admin')->save($data,$map))return $this->error('操作失败');
		$this->success('操作成功');
	}



    //角色管理
    //*+------------------------------------------------------------------------+*/


    //列表页面
    public function role(){
        $list = model("auth_group")->field("description",true)->order("sort desc,id asc")->select();
        $this->assign('list',$list);
        return $this->fetch();
    }


    //修改权限组信息
    public function roledit(){
        $id = input('id');
        if(request()->isPost()){
            $data = request()->post();

            // 验证
            $result=$this->validate($data,'app\admin\validate\GroupValidate');
            if(true!==$result) return $this->error($result);

            $data['rules'] = $data['ids'] ;
            if(empty($data['rules'])) return $this->error('请选择权限节点');
            $data['column'] = $data['cids'] ;

            //添加修改数据
            $this->editDataMethod($data,'AuthGroup');
        }

        if($id) {
            $ag = model('AuthGroup');
            $info = $ag->where('id', $id)->find();
            $this->assign('info',$info);
        }

        //权限节点
        $ids = [];
        if($info['rules'])$ids = explode(',', $info['rules']);
        $this->assign('ids',$ids);

        //文章栏目节点
        $cids = [];
        if($info['column'])$cids = explode(',', $info['column']);
        $this->assign('cids',$cids);

        /*权限节点*/
        $map['manage_show']=1;
        $list = db('menu')->where($map)->order('level ASC,sort DESC')->select();
        $this->assign('list',$list);
        $this->assign('menulen',count($list));

        /*栏目节点*/
        //$colary= db('Navigate')->field("id,title,pid,level")->select();
        //$this->assign('colary',$colary);
        //$this->assign('collen',count($colary));

        return $this->fetch();
    }


    //删除权限组
    public function roledel(){
        $this->delete('AuthGroup');
    }


    //修改权限组状态
    public function rolestate(){
        $this->state('AuthGroup');
    }


    //权限组排序
    public function rolesort(){
        $this->sort('AuthGroup');
    }

}
